package com.qlyl.modules.information.service.impl;

import com.qlyl.common.util.consumer.GsonUtil;
import com.qlyl.modules.information.service.INewsService;
import com.qlyl.modules.information.vo.NewsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.validation.constraints.Min;
import java.util.List;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

//@Service
public class NewsServiceImpl implements INewsService {

    private static final String NEWS_REDIS_KEY = "news";
    private static final String NEWS_SIZE_REDIS_KEY = "news:size";

    @Autowired
    private RedisTemplate redisTemplate;

    public void addNews(NewsVo newsVo) {
        Integer l = (Integer) redisTemplate.opsForValue().get(NEWS_SIZE_REDIS_KEY);
        if (l == null || l == 0) newsVo.setId(-1);
        else newsVo.setId(-1 - l.intValue());
        redisTemplate.opsForList().leftPush(NEWS_REDIS_KEY, GsonUtil.current().toJson(newsVo));
        redisTemplate.opsForValue().increment(NEWS_SIZE_REDIS_KEY);
    }

    public List<NewsVo> getNewsList(long start, long limit) {
        List<String> lis = redisTemplate.opsForList().range(NEWS_REDIS_KEY, start, start + limit - 1);
        return lis.stream().map(j -> GsonUtil.current().fromJson(j, NewsVo.class)).collect(toList());
    }

    public long deleteNews(long index) {
        String temp = (String) redisTemplate.opsForList().index(NEWS_REDIS_KEY, index);
        return redisTemplate.opsForList().remove(NEWS_REDIS_KEY, -1, temp);
    }
}
